﻿using SRB.Tg.Operate;
using SRB.Tg.Operate.Operate;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teigha.DatabaseServices;
using Teigha.Export_Import;
using Teigha.Geometry;
using Teigha.GraphicsSystem;
using Teigha.Runtime;

namespace SRB.Tg.DrawingStandard
{
    public static class LayoutTools
    {
        
        #region 布局
        public static ObjectId CreatLayout(this Database db, string Name, string TKPath, bool isA1 = false, int NumPDF = 1)
        {
            ObjectId curLayId;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary lays = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary;

                if (!lays.Contains(Name))
                {
                    curLayId = LayoutManager.Current.CreateLayout(Name);
                }
                else
                {
                    //LayoutManager.Current.DeleteLayout(Name);
                    //curLayId = LayoutManager.Current.CreateLayout(Name);
                    curLayId = LayoutManager.Current.GetLayoutId(Name);
                }
                for (int page = 0; page < NumPDF; page++)
                {
                    if (isA1)
                        db.XrefAttachAndInsert(TKPath, curLayId, Point3d.Origin.C3D(page * 841));
                    else
                        db.XrefAttachAndInsert(TKPath, curLayId, Point3d.Origin.C3D(page * 420));
                }
                LayoutManager.Current.CurrentLayout = Name;
                var lay = (Layout)tr.GetObject(curLayId, OpenMode.ForWrite);
                if (!isA1)
                    lay.SetPlotSettings("ISO_full_bleed_A3_(420.00_x_297.00_MM)", "monochrome.ctb", "DWG To PDF.pc3");
                else
                    lay.SetA1PlotSettings("ISO_full_bleed_A1_(841.00_x_594.00_MM)", "monochrome.ctb", "DWG To PDF.pc3");
                tr.Commit();
            }
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayoutManager LM = LayoutManager.Current;
                DBDictionary LayoutDict = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                Layout CurrentLo = tr.GetObject(curLayId, OpenMode.ForRead) as Layout;
                BlockTableRecord BlkTblRec = tr.GetObject(CurrentLo.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId ID in BlkTblRec)
                {
                    Viewport VP = tr.GetObject(ID, OpenMode.ForRead) as Viewport;
                    if (VP != null)
                    {
                        VP.UpgradeOpen();
                        VP.Erase();
                    }
                }
                try
                {
                    if (LM.GetLayoutId("布局1") != null)
                    {
                        LM.DeleteLayout("布局1");
                    }
                    if (LM.GetLayoutId("布局2") != null)
                    {
                        LM.DeleteLayout("布局2");
                    }

                    if (LM.GetLayoutId("layout1") != null)
                    {
                        LM.DeleteLayout("layout1");
                    }
                    if (LM.GetLayoutId("layout2") != null)
                    {
                        LM.DeleteLayout("layout2");
                    }
                }
                catch
                {            
                }

                LM.CurrentLayout = "Model";

                tr.Commit();
            
            }

            return curLayId;
        }
        public static ObjectId CreatLayoutNew(this Database db, string Name, string TKPath, bool isA1 = false, int NumPDF = 1, int pageNo = 0, int divNo = 0)
        {
            ObjectId curLayId;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary lays = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary;
                //var acLayoutMgr = LayoutManager.Current;
              
                if (!lays.Contains(Name))
                {
                    curLayId = LayoutManager.Current.CreateLayout(Name);
                }
                else
                {
                    curLayId = LayoutManager.Current.GetLayoutId(Name);
                }
  
                for (int page = 0; page < NumPDF; page++)
                {
                    if (isA1)
                        db.XrefAttachAndInsert(TKPath, curLayId, Point3d.Origin.C3D(page * 841).C3D(841 * divNo, -594 * pageNo));
                    else
                        db.XrefAttachAndInsert(TKPath, curLayId, Point3d.Origin.C3D(page * 420).C3D(420 * divNo, -297 * pageNo));            
                }
                LayoutManager.Current.CurrentLayout = Name;
                var lay = (Layout)tr.GetObject(curLayId, OpenMode.ForWrite);
                if (!isA1)
                    lay.SetPlotSettings("ISO_full_bleed_A3_(420.00_x_297.00_MM)", "monochrome.ctb", "DWG To PDF.pc3");
                else
                    lay.SetA1PlotSettings("ISO_full_bleed_A1_(841.00_x_594.00_MM)", "monochrome.ctb", "DWG To PDF.pc3");
                tr.Commit();
            }
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayoutManager LM = LayoutManager.Current;
                DBDictionary LayoutDict = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                Layout CurrentLo = tr.GetObject(curLayId, OpenMode.ForRead) as Layout;
                BlockTableRecord BlkTblRec = tr.GetObject(CurrentLo.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId ID in BlkTblRec)
                {
                    Viewport VP = tr.GetObject(ID, OpenMode.ForRead) as Viewport;
                    if (VP != null)
                    {
                        VP.UpgradeOpen();
                        VP.Erase();
                    }
                }
                try
                {
                    if (LM.GetLayoutId("布局1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("布局1");
                    }
                    if (LM.GetLayoutId("布局2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("布局2");
                    }
                    if (LM.GetLayoutId("Layout1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("Layout1");
                    }
                    if (LM.GetLayoutId("Layout2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("Layout2");
                    }
                    if (LM.GetLayoutId("layout1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("layout1");
                    }
                    if (LM.GetLayoutId("layout2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("layout2");
                    }
                }
                catch
                {
                }

                LM.CurrentLayout = "Model";

                tr.Commit();

            }
            return curLayId;
        }
        public static ObjectId CreatLayout(this Database db, string Name, string TKPath,bool isCustom=true,double Lw=420,double Lh=297)
        {
            ObjectId curLayId;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary lays = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary;
                
                if (!lays.Contains(Name))
                {
                    curLayId = LayoutManager.Current.CreateLayout(Name);
                }
                else
                {
                    //LayoutManager.Current.DeleteLayout(Name);
                    //curLayId = LayoutManager.Current.CreateLayout(Name);
                    curLayId = LayoutManager.Current.GetLayoutId(Name);
                }

                for (int page = 0; page < 1; page++)
                {
                    if (isCustom)
                    {
                        db.XrefAttachAndInsert(TKPath, curLayId, Point3d.Origin.C3D());
                    }                   
                }
                LayoutManager.Current.CurrentLayout = Name;
                var lay = (Layout)tr.GetObject(curLayId, OpenMode.ForWrite);
                if (isCustom)
                {
 
                    lay.SetCustomPlotSettings("Custom ("+Lw+".00_x_"+Lh+".00_MM)", "monochrome.ctb", "DWG To PDF.pc3",Lw,Lh);
                    //lay.SetCustomPlotSettings("Custom (" + Lw + ".00_x_" + Lh + ".00_MM)", "monochrome.ctb", "DWG To PDF.pc3", Lw, Lh);
                }
                tr.Commit();
            }
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayoutManager LM = LayoutManager.Current;
                DBDictionary LayoutDict = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                Layout CurrentLo = tr.GetObject(curLayId, OpenMode.ForRead) as Layout;
                BlockTableRecord BlkTblRec = tr.GetObject(CurrentLo.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId ID in BlkTblRec)
                {
                    Viewport VP = tr.GetObject(ID, OpenMode.ForRead) as Viewport;
                    if (VP != null)
                    {
                        VP.UpgradeOpen();
                        VP.Erase();
                    }
                }
                try
                {
                    if (LM.GetLayoutId("布局1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("布局1");
                    }
                    if (LM.GetLayoutId("布局2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("布局2");
                    }
                    if (LM.GetLayoutId("Layout1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("Layout1");
                    }
                    if (LM.GetLayoutId("Layout2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("Layout2");
                    }
                    if (LM.GetLayoutId("layout1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("layout1");
                    }
                    if (LM.GetLayoutId("layout2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("layout2");
                    }
                }
                catch
                {
                }

                LM.CurrentLayout = "Model";

                tr.Commit();

            }

            return curLayId;
        }

        public static ObjectId CreatLayoutNew(this Database db, string Name, string TKPath, bool isA1 = false, int NumPDF = 1, int RowNo = 1)
        {
            ObjectId curLayId;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary lays = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary;

                if (!lays.Contains(Name))
                {
                    curLayId = LayoutManager.Current.CreateLayout(Name);
                }
                else
                {
                    curLayId = LayoutManager.Current.GetLayoutId(Name);
                }
                for (int page = 0; page < NumPDF; page++)
                {
                    for (int i = 0; i < RowNo; i++)
                    {
                        if (isA1)
                            db.XrefAttachAndInsert(TKPath, curLayId, Point3d.Origin.C3D(page * 841).C3D(0, -594 * i));
                        else
                            db.XrefAttachAndInsert(TKPath, curLayId, Point3d.Origin.C3D(page * 420).C3D(0, -297 * i));
                    }
                }
                LayoutManager.Current.CurrentLayout = Name;
                var lay = (Layout)tr.GetObject(curLayId, OpenMode.ForWrite);
                if (!isA1)
                    lay.SetPlotSettings("ISO_full_bleed_A3_(420.00_x_297.00_MM)", "monochrome.ctb", "DWG To PDF.pc3");
                else
                    lay.SetA1PlotSettings("ISO_full_bleed_A1_(841.00_x_594.00_MM)", "monochrome.ctb", "DWG To PDF.pc3");
                tr.Commit();
            }
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayoutManager LM = LayoutManager.Current;
                DBDictionary LayoutDict = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                Layout CurrentLo = tr.GetObject(curLayId, OpenMode.ForRead) as Layout;
                BlockTableRecord BlkTblRec = tr.GetObject(CurrentLo.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId ID in BlkTblRec)
                {
                    Viewport VP = tr.GetObject(ID, OpenMode.ForRead) as Viewport;
                    if (VP != null)
                    {
                        VP.UpgradeOpen();
                        VP.Erase();
                    }
                }
                try
                {
                    if (LM.GetLayoutId("布局1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("布局1");
                    }
                    if (LM.GetLayoutId("布局2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("布局2");
                    }
                    if (LM.GetLayoutId("Layout1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("Layout1");
                    }
                    if (LM.GetLayoutId("Layout2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("Layout2");
                    }
                    if (LM.GetLayoutId("layout1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("layout1");
                    }
                    if (LM.GetLayoutId("layout2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("layout2");
                    }
                }
                catch
                {
                }

                LM.CurrentLayout = "Model";

                tr.Commit();

            }

            return curLayId;
        }
        public static ObjectId CreatDefpointsLayout(this Database db, string Name, string TKPath, bool isA1 = false, int NumPDF = 1, int RowNo = 1)
        {
            ObjectId curLayId;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary lays = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary;

                if (!lays.Contains(Name))
                {
                    curLayId = LayoutManager.Current.CreateLayout(Name);
                }
                else
                {
                    curLayId = LayoutManager.Current.GetLayoutId(Name);
                }
                for (int page = 0; page < NumPDF; page++)
                {
                    for (int i = 0; i < RowNo; i++)
                    {
                        if (isA1)
                            db.XrefAttachAndInsertDefpoints(TKPath, curLayId, Point3d.Origin.C3D(page * 841).C3D(0, -594 * i));
                        else
                            db.XrefAttachAndInsertDefpoints(TKPath, curLayId, Point3d.Origin.C3D(page * 420).C3D(0, -297 * i));
                    }
                }
                LayoutManager.Current.CurrentLayout = Name;
                var lay = (Layout)tr.GetObject(curLayId, OpenMode.ForWrite);
                if (!isA1)
                    lay.SetPlotSettings("ISO_full_bleed_A3_(420.00_x_297.00_MM)", "monochrome.ctb", "DWG To PDF.pc3");
                else
                    lay.SetA1PlotSettings("ISO_full_bleed_A1_(841.00_x_594.00_MM)", "monochrome.ctb", "DWG To PDF.pc3");
                tr.Commit();
            }
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayoutManager LM = LayoutManager.Current;
                DBDictionary LayoutDict = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                Layout CurrentLo = tr.GetObject(curLayId, OpenMode.ForRead) as Layout;
                BlockTableRecord BlkTblRec = tr.GetObject(CurrentLo.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId ID in BlkTblRec)
                {
                    Viewport VP = tr.GetObject(ID, OpenMode.ForRead) as Viewport;
                    if (VP != null)
                    {
                        VP.UpgradeOpen();
                        VP.Erase();
                    }
                }
                try
                {
                    if (LM.GetLayoutId("布局1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("布局1");
                    }
                    if (LM.GetLayoutId("布局2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("布局2");
                    }
                    if (LM.GetLayoutId("Layout1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("Layout1");
                    }
                    if (LM.GetLayoutId("Layout2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("Layout2");
                    }
                    if (LM.GetLayoutId("layout1") != ObjectId.Null)
                    {
                        LM.DeleteLayout("layout1");
                    }
                    if (LM.GetLayoutId("layout2") != ObjectId.Null)
                    {
                        LM.DeleteLayout("layout2");
                    }
                }
                catch
                {
                }

                LM.CurrentLayout = "Model";

                tr.Commit();

            }

            return curLayId;
        }
        /// <summary>
        /// 引入并插入参照
        /// </summary>
        /// <param name="db"></param>
        /// <param name="path"></param>
        /// <param name="paperSpaceId"></param>
        /// <param name="pos"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool XrefAttachAndInsert(this Database db, string path, ObjectId paperSpaceId, Point3d pos, string name = null)
        {
            var ret = false;
            if (!File.Exists(path))
                return ret;

            if (String.IsNullOrEmpty(name))
                name = Path.GetFileNameWithoutExtension(path);

            try
            {
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                    var xId = db.AttachXref(path, name);
                    if (xId.IsValid)
                    {
                        Layout tmp = (Layout)tr.GetObject(paperSpaceId, OpenMode.ForWrite);
                        var btr = (BlockTableRecord)tr.GetObject(tmp.BlockTableRecordId, OpenMode.ForWrite);
                        var br = new BlockReference(pos, xId);
                        br.LayerId = lt["H图框"];
                        btr.AppendEntity(br);
                        tr.AddNewlyCreatedDBObject(br, true);
                        ret = true;
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            { }

            return ret;
        }

        public static bool XrefAttachAndInsertDefpoints(this Database db, string path, ObjectId paperSpaceId, Point3d pos, string name = null)
        {
            var ret = false;
            if (!File.Exists(path))
                return ret;

            if (String.IsNullOrEmpty(name))
                name = Path.GetFileNameWithoutExtension(path);

            try
            {
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                    var xId = db.AttachXref(path, name);
                    if (xId.IsValid)
                    {
                        Layout tmp = (Layout)tr.GetObject(paperSpaceId, OpenMode.ForWrite);
                        var btr = (BlockTableRecord)tr.GetObject(tmp.BlockTableRecordId, OpenMode.ForWrite);
                        var br = new BlockReference(pos, xId);
                        br.LayerId = lt["H不打印图框"];
                        btr.AppendEntity(br);
                        tr.AddNewlyCreatedDBObject(br, true);
                        ret = true;
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            { }

            return ret;
        }

        public static void SetPlotSettings(this Layout lay, string pageSize, string styleSheet, string device)
        {
            using (var ps = new PlotSettings(lay.ModelType))
            {
                ps.CopyFrom(lay);
                var psv = PlotSettingsValidator.Current;
                //psv.Dispose();
                // Set the device
                var devs = psv.GetPlotDeviceList();
                if (ps.PlotConfigurationName != device)
                {
                    if (devs.Contains(device))
                    {
                        if (ps.PlotConfigurationName != device)
                            psv.SetPlotConfigurationName(ps, device, null);
                        psv.RefreshLists(ps);
                    }

                    // Set the media name/size
                    var mns = psv.GetCanonicalMediaNameList(ps);
                    if (mns.Contains(pageSize))
                    {
                        if (ps.CanonicalMediaName != pageSize)
                            psv.SetCanonicalMediaName(ps, pageSize);
                    }
                    //设置打印区域SetPlotType
                    //psv.SetPlotType(ps, PlotType.Window);
                    //psv.SetPlotWindowArea(ps, extents);
                    psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(420, 297)));
                    //psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(520, 297)));

                    psv.RefreshLists(ps);
                    psv.SetPlotRotation(ps, PlotRotation.Degrees000);

                    //psv.SetPlotCentered(ps, true);
                    psv.SetCustomPrintScale(ps, new CustomScale(1, 1));
                    psv.SetPlotType(ps, PlotType.Window);
                    psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);//设置的单位
                    psv.SetStdScaleType(ps, StdScaleType.StdScale1To1);//设置比例
                                                                       //psv.SetPlotCentered(ps, true);
                                                                       // Set the pen settings
                 
            
                    var ssl = psv.GetPlotStyleSheetList();
                    if (ssl.Contains(styleSheet))
                    {
                        psv.SetCurrentStyleSheet(ps, styleSheet);
                    }
                    // Copy the PlotSettings data back to the Layout
                }
                var upgraded = false;
                if (!lay.IsWriteEnabled)
                {
                    lay.UpgradeOpen();
                    upgraded = true;
                }
                lay.CopyFrom(ps);
                if (upgraded)
                {
                    lay.DowngradeOpen();
                }
            }
        }
    
        static double calcDiagonal(object point1, object point2)
        {
            double length = Math.Abs(((double[])point1)[0] - ((double[])point2)[0]);
            double height = Math.Abs(((double[])point1)[1] - ((double[])point2)[1]);

            double result = Math.Sqrt(length * length + height * height);//对角线
            return result;
        }
        public static void SetA1PlotSettings(this Layout lay, string pageSize, string styleSheet, string device)
        {
            using (var ps = new PlotSettings(lay.ModelType))
            {

                ps.CopyFrom(lay);
                var psv = PlotSettingsValidator.Current;
                // Set the device
                var devs = psv.GetPlotDeviceList();
                if (devs.Contains(device))//设置设备
                {
                    psv.SetPlotConfigurationName(ps, device, null);
                    psv.RefreshLists(ps);
                }
                // Set the media name/size
                var mns = psv.GetCanonicalMediaNameList(ps);

                if (mns.Contains(pageSize))//设置纸张大小
                {
                    psv.SetCanonicalMediaName(ps, pageSize);
                }
                //psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(841, 594)));//设置打印纸张大小范围
                //                                                                                   //psv.SetPlotType(ps, PlotType.Window);//设置打印范围
                //                                                                                   //psv.SetStdScale(ps, 1);//设置标准比例

                //psv.SetCustomPrintScale(ps, new CustomScale(1, 1));
                //psv.SetUseEnScale(ps, true);
                psv.SetStdScaleType(ps, StdScaleType.StdScale1To1);//设置比例
                psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);//设置的单位
                //psv.SetPlotRotation(ps, PlotRotation.Degrees000);//设置横向;纵向Degrees270

                //psv.SetStdScale(ps, 1);
                //psv.SetPlotType(ps, PlotType.Layout);//设置打印范围

                psv.RefreshLists(ps);
                psv.SetPlotRotation(ps, PlotRotation.Degrees000);
                psv.SetCustomPrintScale(ps, new CustomScale(1, 1));
                psv.SetPlotWindowArea(ps, new Extents2d(1, 0, 841, 594));
                psv.SetPlotType(ps, PlotType.Window);
                var ssl = psv.GetPlotStyleSheetList();
                if (ssl.Contains(styleSheet))
                {
                    psv.SetCurrentStyleSheet(ps, styleSheet);
                    //psv.
                }
                // Copy the PlotSettings data back to the Layout

                var upgraded = false;
                if (!lay.IsWriteEnabled)
                {
                    lay.UpgradeOpen();
                    upgraded = true;
                }
                lay.CopyFrom(ps);
                if (upgraded)
                {
                    lay.DowngradeOpen();
                }
            }
        }

        public static void SetCustomPlotSettings(this Layout lay, string pageSize, string styleSheet, string device, double Lw=420, double Lh=297)
        {
            try
            {
         
                lay.UpgradeOpen();
                using (var ps = new PlotSettings(lay.ModelType))
                {
                    ps.CopyFrom(lay);
                    var psv = PlotSettingsValidator.Current;
                 
                    var upgraded = true;
                    //psv.Dispose();
                    // Set the device
                    //psv.SetClosestMediaName(ps, Lw, Lh, PlotPaperUnit.Millimeters, false);
                    var devs = psv.GetPlotDeviceList();
                    if (ps.PlotConfigurationName != device)
                    {
                        if (devs.Contains(device))
                        {
                            if (ps.PlotConfigurationName != device)
                                psv.SetPlotConfigurationName(ps, device, null);
                            psv.RefreshLists(ps);
                        }
                      
                        // Set the media name/size
                        var mns = psv.GetCanonicalMediaNameList(ps);
                        var mns0 = psv.GetLocaleMediaName(ps, 8);
                        if (mns.Contains(pageSize))
                        {
                            if (ps.CanonicalMediaName != pageSize)
                                psv.SetCanonicalMediaName(ps, pageSize);
                        }
                        else
                        {
                            //psv.(ps, pageSize);
                            string config = "ISO_full_bleed_A3_(420.00_x_297.00_MM)";
                     
                            //psv.RefreshLists(ps);
                            psv.SetClosestMediaName(ps, Lw, Lh, PlotPaperUnit.Millimeters, true);
                            //psv.SetClosestMediaName(ps, Lw, Lh, PlotPaperUnit.Millimeters, true);
                            string configCustom = " UserDefinedMetric (1400.00 x 297.00 毫米)";
                            string configC = psv.GetLocaleMediaName(ps, configCustom);
                            var mns00 = psv.GetLocaleMediaName(ps, 1);
                            //psv.SetCanonicalMediaName(ps, configCustom);
                            psv.RefreshLists(ps);

                        }

                        //psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(Lw, Lh)));
                        //psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(1, 297)));

                        //psv.RefreshLists(ps);
                        psv.SetPlotRotation(ps, PlotRotation.Degrees000);

                        psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(Lw, Lh)));
                        psv.SetPlotType(ps, PlotType.Window);
                        psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(Lw, Lh)));
                        psv.SetCustomPrintScale(ps, new CustomScale(1, 1));

                        psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);//设置的单位
                        psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);//设置比例
                    
                        //PlotInfoValidator infoValidator = new PlotInfoValidator();
                        //infoValidator.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                        //infoValidator.Validate(info);
                        //psv.SetPlotCentered(ps, true);

                        //psv.SetPlotCentered(ps, true);
                        // Set the pen settings
                        //var ssl = psv.GetPlotStyleSheetList();
                        //if (ssl.Contains(styleSheet))
                        //{
                        //    psv.SetCurrentStyleSheet(ps, styleSheet);
                        //}
                        // Copy the PlotSettings data back to the Layout
                    }
                    //var upgraded = false;
                    //if (!lay.IsWriteEnabled)
                    //{
                    //    lay.UpgradeOpen();
                    //    upgraded = true;
                    //}

                    lay.CopyFrom(ps);
                    if (upgraded)
                    {
                        lay.DowngradeOpen();
                    }
                }
            }
            catch(System.Exception ex)
            {

            }
        }

        #endregion

        #region  视口
        public static void CreateViewport(Database db, ObjectId LayoutId, double W, double L, Point2d PSCenter, Point2d MSCenter, double scale)
        {

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {

                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                Layout lay = (Layout)tr.GetObject(LayoutId, OpenMode.ForWrite);
                UcsTable ut = tr.GetObject(db.UcsTableId, OpenMode.ForRead) as UcsTable;
                var btr = (BlockTableRecord)tr.GetObject(lay.BlockTableRecordId, OpenMode.ForWrite);

                // 平面视口
                Viewport vpFlat = new Viewport();
                btr.AppendEntity(vpFlat);
                tr.AddNewlyCreatedDBObject(vpFlat, true);
                vpFlat.LayerId = lt["Defpoints"];
                vpFlat.On = true;
                vpFlat.GridOn = false;
                vpFlat.SettingSizeAndLoc(W, L, PSCenter, scale);
                vpFlat.ViewCenter = MSCenter;
                vpFlat.Visible = true;
              
                //viewCenter = vpFlat.ViewCenter;
                //vpFlat.ViewCenter = new Point2d((pt.X+ offset+ offsetY + areaWidth) /2, (pt.Y + areaHeight) /2);
                tr.Commit();
            }

            return;
        }

        public static void CreateViewportRotate(Database db, ObjectId LayoutId, double W,
            double L, Point2d PSCenter, Point2d MSCenter, int scale, double angle = 90)
        {
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Layout lay = (Layout)tr.GetObject(LayoutId, OpenMode.ForWrite);
                UcsTable ut = tr.GetObject(db.UcsTableId, OpenMode.ForWrite) as UcsTable;
                var btr = (BlockTableRecord)tr.GetObject(lay.BlockTableRecordId, OpenMode.ForWrite);
                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                // 平面视口
                Viewport vpFlat = new Viewport();
                
                btr.AppendEntity(vpFlat);
                vpFlat.Rotate(PSCenter.C3D(), GeTools.DegreeToRadian(angle));
                tr.AddNewlyCreatedDBObject(vpFlat, true);
                vpFlat.LayerId = lt["Defpoints"];
                vpFlat.On = true;
                vpFlat.GridOn = false;
                vpFlat.SettingSizeAndLoc(W, L, PSCenter, scale);
                vpFlat.ViewCenter = MSCenter;
                vpFlat.Visible = true;
                //vpFlat.Rotate(PSCenter.C3D(), GeTools.DegreeToRadian(angle));

                //Viewport vpFlat1 = new Viewport();
                //btr.AppendEntity(vpFlat1);
                //tr.AddNewlyCreatedDBObject(vpFlat1, true);
                //vpFlat1.LayerId = lt["Defpoints"];
                //vpFlat1.On = true;
                //vpFlat1.GridOn = false;
                //vpFlat1.SettingSizeAndLoc( L, W, PSCenter, scale);
                //vpFlat1.ViewCenter = MSCenter;
                //vpFlat1.Visible = true;
                ////vpFlat1.Rotate(PSCenter.C3D(), GeTools.DegreeToRadian(angle));
                //vpFlat.TwistAngle = GeTools.DegreeToRadian(270);
                //vpFlat.Rotate(PSCenter.C3D(), GeTools.DegreeToRadian(angle));
                //viewCenter = vpFlat.ViewCenter;
                //vpFlat.ViewCenter = new Point2d((pt.X+ offset+ offsetY + areaWidth) /2, (pt.Y + areaHeight) /2);
                tr.Commit();
          
            }
            return;
        }

        /// <summary>
        /// 平面\立面视口.
        /// </summary>
        public static void SettingSizeAndLoc(this Viewport vp, double w, double h, Point2d basepoint, double scale)
        {
            vp.Width = w;
            vp.Height = h;
            vp.CenterPoint = basepoint.C3D();
            vp.CustomScale = 1.0 / scale;
            vp.Locked = false;
        }

        /// <summary>
        /// 上二下二四视口布局
        /// </summary>
        /// <param name="db"></param>
        /// <param name="layoutName"></param>
        /// <param name="extTL">上部左侧对应的范围</param>
        /// <param name="extTR">上部右侧对应的范围</param>
        /// <param name="extBL">下部左侧对应的范围</param>
        /// <param name="extBR">上部右侧对应的范围</param>
        /// <param name="MarginL">图框左侧边距</param>
        /// <param name="MarginR">图框右侧边距</param>
        /// <param name="MarginB">图框底部边距</param>
        /// <param name="MarginT">图框顶部边距</param>
        /// <param name="scale">对应比例尺</param>
        /// <param name="isA1">A1或者A3图框</param>
        /// <param name="tkPath"></param>
        /// <returns></returns>
        public static ObjectId CreateLayout4Div(Database db, string layoutName,
         Extents2d extTL, Extents2d extTR, Extents2d extBL, Extents2d extBR,
         double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
                //ArrangeLayoutId = db.CreatLayout(layoutName, "",true,1422,297, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double VPWidth1 = Math.Max(extTL.W(), extBL.W()) / scale;
            double VPHight1 = Math.Max(extTL.L(), extTR.L()) / scale;
            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);

            double wA = w * (extTL.W() / (extTL.W() + extTR.W()));  //上部左侧视口长度
            double wB = w * (extTR.W() / (extTL.W() + extTR.W()));  //上部右侧视口长度
            double hA = h * (extTL.L() / (extTL.L() + extBL.L()));  //上部左侧视口高度
            double hP = h * (extBL.L() / (extTL.L() + extBL.L()));  //下部左侧视口高度

            double M1 = MarginL + wA;  //上部右侧视口位置
            double M2 = MarginB + hP;  //上部右侧视口位置
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extTL.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extTL.W() / scale + 5, extTL.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + wA * 0.5, M2 + 0.5 * hA),
                extTL.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extTR.W() / scale + 5, extTR.L() / scale + 5,
                Point2d.Origin.C2D(M1 + wB * 0.5, M2 + 0.5 * hA),
                extTR.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extBL.W() / scale + 5, extBL.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + 0.5 * wA, MarginB + 0.5 * hP),
                extBL.GetCenter(), (int)scale);


            CreateViewport(db, ArrangeLayoutId, extBR.W() / scale + 5, extBR.L() / scale + 5,
            Point2d.Origin.C2D(M1 + wB * 0.5, MarginB + 0.5 * hP),
            extBR.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }

        public static ObjectId CreateLayout2LRDiv(Database db, string layoutName,
 Extents2d extTL, Extents2d extBL, Extents2d extR,
 double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
                //ArrangeLayoutId = db.CreatLayout(layoutName, "",true,1422,297, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double VPWidth1 = Math.Max(extTL.W(), extBL.W()) / scale;
            double VPHight1 = Math.Max(extTL.L(), extR.L()) / scale;
            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);

            double wA = w * (extTL.W() / (extTL.W() + extR.W()));  //上部左侧视口长度
            double wB = w * (extR.W() / (extTL.W() + extR.W()));  //上部右侧视口长度
            double hA = h * (extTL.L() / (extTL.L() + extBL.L()));  //上部左侧视口高度
            double hP = h * (extBL.L() / (extTL.L() + extBL.L()));  //下部左侧视口高度

            double M1 = MarginL + wA;  //上部右侧视口位置
            double M2 = MarginB + hP;  //上部右侧视口位置
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extTL.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extTL.W() / scale + 5, extTL.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + wA * 0.5, M2 + 0.5 * hA),
                extTL.GetCenter(), (int)scale);
       

            CreateViewport(db, ArrangeLayoutId, extBL.W() / scale + 5, extBL.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + 0.5 * wA, MarginB + 0.5 * hP),
                extBL.GetCenter(), (int)scale);


            CreateViewport(db, ArrangeLayoutId, extR.W() / scale + 5, extR.L() / scale + 5,
            Point2d.Origin.C2D(M1 + wB * 0.5, MarginB + 0.5 * h),
            extR.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }
        /// <summary>
        /// 自动创建上中下三视口布局
        /// </summary>
        /// <param name="db"></param>
        /// <param name="layoutName">布局名称</param>
        /// <param name="extT">上部视口对应的范围</param>
        /// <param name="extM">中部视口对应的范围</param>
        /// <param name="extB">下部视口对应的范围</param>
        /// <param name="MarginL">图框左侧边距</param>
        /// <param name="MarginR">图框右侧边距</param>
        /// <param name="MarginB">图框底部边距</param>
        /// <param name="MarginT">图框顶部边距</param>
        /// <param name="scale">对应比例尺</param>
        /// <param name="isA1">A1或者A3图框</param>
        /// <returns></returns>

        public static ObjectId CreateLayout3Div(Database db, string layoutName,
               Extents2d extT, Extents2d extM, Extents2d extB,
               double MarginL, double MarginR, double MarginB, double MarginT, double scale,bool isA1=false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }
           
            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double hA = h * (extT.L() / (extT.L() + extM.L() + extB.L()));  //上部视口高度
            double hP = h * (extM.L() / (extT.L() + extM.L() + extB.L()));  //中部视口高度
            double hD = h * (extB.L() / (extT.L() + extM.L() + extB.L()));  //下部视口高度
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extT.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extT.W() / scale + 5, extT.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + w * 0.5, MarginB + hD + hP + 0.5 * hA),
                extT.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extM.W() / scale + 5, extM.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + w * 0.5, MarginB + hD + 0.5 * hP),
                extM.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extB.W() / scale + 5, extB.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * hD),
                extB.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }

        /// <summary>
        /// 左中右三视口
        /// </summary>
        /// <param name="db"></param>
        /// <param name="layoutName"></param>
        /// <param name="extL">左部视口对应的范围</param>
        /// <param name="extM">中部视口对应的范围</param>
        /// <param name="extR">右部视口对应的范围</param>
        /// <param name="MarginL">图框左侧边距</param>
        /// <param name="MarginR">图框右侧边距</param>
        /// <param name="MarginB">图框底部边距</param>
        /// <param name="MarginT">图框顶部边距</param>
        /// <param name="scale">对应比例尺</param>
        /// <param name="isA1">A1或者A3图框</param>
        /// <returns></returns>
        public static ObjectId CreateLRLayout3Div(Database db, string layoutName,
             Extents2d extL, Extents2d extM, Extents2d extR,
             double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double wL= h * (extL.L() / (extL.L() + extM.L() + extR.L()));  //左部视口高度
            double wM = h * (extM.L() / (extL.L() + extM.L() + extR.L()));  //中部视口高度
            double wR = h * (extR.L() / (extL.L() + extM.L() + extR.L()));  //右部视口高度
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extL.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extL.W() / scale + 5, extL.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + wL * 0.5, MarginB + 0.5 * h),
                extL.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extM.W() / scale + 5, extM.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + wL+wM * 0.5, MarginB +  0.5 * h),
                extM.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extR.W() / scale + 5, extR.L() / scale + 5,
                Point2d.Origin.C2D(MarginL+ wL+wM + 0.5 * w, MarginB + 0.5 * h),
                extR.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }

        /// <summary>
        /// 自动创建上下二视口布局
        /// </summary>
        /// <param name="db"></param>
        /// <param name="layoutName">布局名称</param>
        /// <param name="extT">上部视口对应的范围</param>
        /// <param name="extB">下部视口对应的范围</param>
        /// <param name="MarginL">图框左侧边距</param>
        /// <param name="MarginR">图框右侧边距</param>
        /// <param name="MarginB">图框底部边距</param>
        /// <param name="MarginT">图框顶部边距</param>
        /// <param name="scale">对应比例尺</param>
        /// <param name="isA1">A1或者A3图框</param>
        /// <returns></returns>
        public static ObjectId CreateLayout2Div(Database db, string layoutName,
       Extents2d extT,  Extents2d extB,
       double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double hT = h * (extT.L() / (extT.L()  + extB.L()));  //上部视口高度          
            double hD = h * (extB.L() / (extT.L()  + extB.L()));  //下部视口高度
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extT.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extT.W() / scale + 5, extT.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + w * 0.5, MarginB + hD  + 0.5 * hT),
                extT.GetCenter(), (int)scale);


            CreateViewport(db, ArrangeLayoutId, extB.W() / scale + 5, extB.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * hD),
                extB.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }

        /// <summary>
        /// 自动创建左右二视口布局
        /// </summary>
        /// <param name="db"></param>
        /// <param name="layoutName">布局名称</param>
        /// <param name="extL">左侧视口对应的范围</param>
        /// <param name="extR">右侧视口对应的范围</param>
        /// <param name="MarginL">图框左侧边距</param>
        /// <param name="MarginR">图框右侧边距</param>
        /// <param name="MarginB">图框底部边距</param>
        /// <param name="MarginT">图框顶部边距</param>
        /// <param name="scale">对应比例尺</param>
        /// <param name="isA1">A1或者A3图框</param>
        /// <returns></returns>
        public static ObjectId CreateLRLayout2Div(Database db, string layoutName,
       Extents2d extL, Extents2d extR,
       double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double wL  = w * (extL.W() / (extL.W() + extR.W()));  //上部视口高度          
            double wR  = w * (extR.W() / (extL.W() + extR.W()));  //下部视口高度
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extL.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extL.W() / scale + 5, extL.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + wL * 0.5, MarginB + 0.5 * h),
                extL.GetCenter(), (int)scale);


            CreateViewport(db, ArrangeLayoutId, extR.W() / scale + 5, extR.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + wL+ 0.5 * wR, MarginB + 0.5 * h),
                extR.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }

      
        /// <summary>
        /// 
        /// </summary>
        /// <param name="db"></param>
        /// <param name="layoutName"></param>
        /// <param name="ext">对应的范围</param>
        /// <param name="MarginL">图框左侧边距</param>
        /// <param name="MarginR">图框右侧边距</param>
        /// <param name="MarginB">图框底部边距</param>
        /// <param name="MarginT">图框顶部边距</param>
        /// <param name="scale">对应比例尺</param>
        /// <param name="isA1">A1或者A3图框</param>
        /// <param name="tkPath"></param>
        /// <returns></returns>
        public static ObjectId CreateLayout(string layoutName,
Extents2d ext, double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);

            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), ext.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * h),
                ext.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }
        public static ObjectId CreateLayout(Database db, string layoutName,
Extents2d ext, double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            //Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);

            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), ext.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * h),
                ext.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }
        public static ObjectId CreateLayoutNew(Database db, string layoutName,
Extents2d ext, double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            //Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double ww = ext.W() / scale;
            double hh = ext.L() / scale;
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), ext.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * h+3),
                ext.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }
        public static ObjectId CreateLayoutRotate(Database db, string layoutName,
Extents2d ext, double MarginL, double MarginR, double MarginB, double MarginT, double scale, bool isA1 = false)
        {
            //Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, 1);
            }

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double ww = ext.W() / scale;
            double hh = ext.L() / scale;
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), ext.GetCenter(), (int)scale);
            #endregion
            CreateViewportRotate(db, ArrangeLayoutId,  ext.W() / scale + 15, ext.L() / scale + 15,
                Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * h),
                ext.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }

        public static ObjectId CreateLayout(Database db, string layoutName,
List<Extents2d> extLst, double MarginL, double MarginR, double MarginB, double MarginT, double scale,int index=0, bool isA1 = false)
        {
            //Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, extLst.Count, index);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, extLst.Count, index);
            }
            for (int i = 0; i < extLst.Count; i++)
            {
                Extents2d ext = extLst[i];
          

                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);

                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420*i, -297 * (index-1)), ext.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * h).C2D(420 * i,-297* (index - 1)),
                    ext.GetCenter(), (int)scale);
            }
            return ArrangeLayoutId;
        }

        public static ObjectId CreateTopLayout(Database db, string layoutName,
List<Extents2d> extLst, double MarginL, double MarginR, double MarginB, double MarginT, double scale, int index = 0, bool isA1 = false)
        {
            //Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, extLst.Count, index);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, extLst.Count, index);
            }
            for (int i = 0; i < extLst.Count; i++)
            {
                Extents2d ext = extLst[i];


                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);

                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * i, -297 * (index - 1)), ext.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + h-0.5 * ext.L()-5).C2D(420 * i, -297 * (index - 1)),
                    ext.GetCenter(), (int)scale);
            }
            return ArrangeLayoutId;
        }

        public static ObjectId CreateDefpointsLayout(Database db, string layoutName,
List<Extents2d> extLst, double MarginL, double MarginR, double MarginB, double MarginT, double scale, int index = 0, bool isA1 = false)
        {
            //Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatDefpointsLayout(layoutName, tkPath, isA1, extLst.Count, index);
            }
            else
            {
                ArrangeLayoutId = db.CreatDefpointsLayout(layoutName, "", isA1, extLst.Count, index);
            }
            for (int i = 0; i < extLst.Count; i++)
            {
                Extents2d ext = extLst[i];


                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);

                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * i, -297 * (index - 1)), ext.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + h-0.5* ext.L()-5).C2D(420 * i, -297 * (index - 1)),
                    ext.GetCenter(), (int)scale);
            }
            return ArrangeLayoutId;
        }
        public static ObjectId CreateBlankLayout(Database db, string layoutName,
double MarginL, double MarginR, double MarginB, double MarginT, double scale,int Count, int index = 1, bool isA1 = false)
        {
            //Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, Count, index);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, Count, index);
            }
            for (int i = 0; i < Count; i++)
            {
                Extents2d ext = new Extents2d(Point2d.Origin, Point2d.Origin.C2D(1,1));
                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);

                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * i, -297 * (index - 1)), ext.GetCenter(), (int)scale);
                #endregion       
            }
            return ArrangeLayoutId;
        }
        public static ObjectId CreateLayout(Database db, string layoutName, bool isNullLayout = false, int pdfNum = 1, bool isTitleTab = true, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, pdfNum);
            return ArrangeLayoutId;
        }

        public static ObjectId CreatePileLayout(Database db, string layoutName,
Extents2d extA, Extents2d extB, Extents2d extPlan, Extents2d extDetail,
double MarginL, double MarginR, double MarginB, double MarginT, double scale)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = "";
            if (System.IO.File.Exists(Extensions.curTKPath))
            {
                tkPath = Extensions.curTKPath;
            }
            bool isA1 = false;
            if (Extensions.curMapSheet == "A1")
            {
                isA1 = true;
            }
           
            ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double HA = extA.L() / scale;
            double HB = extB.L() / scale;
            double wA = extA.W() / scale;  //A视口长度
            double wB = extB.W() / scale;  //B视口长度
            double wC = w * 0.5;  //B视口长度
            double M1 = MarginL + wA + 10;  //B视口位置
            double M2 = MarginB;  //B视口位置

            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extA.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extA.W() / scale + 5, extA.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + wA * 0.5, M2 + 0.5 * HA),
                extA.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extB.W() / scale + 5, extB.L() / scale + 5,
                Point2d.Origin.C2D(M1 + wB * 0.5, M2 + 0.5 * HB),
                extB.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extPlan.W() / scale + 5, extPlan.L() / scale + 5,
                Point2d.Origin.C2D(M1 + extPlan.W() / scale * 0.5, M2 + HB + (h - HB) * 0.5),
                extPlan.GetCenter(), (int)scale);


            CreateViewport(db, ArrangeLayoutId, extDetail.W() / scale + 5, extDetail.L() / scale + 5,
               Point2d.Origin.C2D(M1 + wB + 5 + extDetail.W() * 0.5 / scale, MarginB + 0.55 * h * 0.5),
               extDetail.GetCenter(), (int)scale);
            //CreateViewport(db, ArrangeLayoutId, extDetail.W() / scale, extDetail.L() / scale,
            //Point2d.Origin.C2D(MarginL + MarginB*3+ extA.W() / scale+ extB.W() / scale + extDetail.L() / scale * 0.5,
            //M2 + 0.5 * HB),
            //extDetail.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }


        public static ObjectId CreateSerPileLayout(Database db, string layoutName,
Extents2d extP, Extents2d extS, List<Extents2d> extD, Extents2d ExtCal,
double MarginL, double MarginR, double MarginB, double MarginT, double scale,ref Point2d tKPoint)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = "";
            //if (System.IO.File.Exists(Extensions.curTKPath))
            //{
            //    tkPath = Extensions.curTKPath;
            //}
            bool isA1 = false;
            if (Extensions.curMapSheet == "A1")
            {
                isA1 = true;
            }
            scale = 5;
            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double hP = extP.L() / scale;
            double wP = extP.W() / scale;  //A视口长度
            double wS = extS.W() / scale;  //视口位置
            double hS = extS.L() / scale;  //视口位置
            double W = wP + wS + 10;
            double wTK = W + MarginL + MarginR + 185;
            int len = (int)(wTK - 25) % 185;
            if ((wTK - 25) % 185 != 0&&len>80)
                wTK = 25 + ((int)((wTK - 25) / 185) + 1) * 185;
            else
                wTK = 25 + ((int)((wTK - 25) / 185)) * 185;
            ArrangeLayoutId = db.CreatLayout(layoutName, tkPath,true, wTK, 297);
            //ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
           

        
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extP.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extP.W() / scale + 5, extP.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + wP * 0.5+5,297- MarginT - hP*0.5-3),
                extP.GetCenter(), (int)scale);
            double M1 = MarginL + wP+5;  //视口位置
   
         
            double wCal = ExtCal.W() / scale;  //视口位置
            double wPartTow = wS;
            if (wS/ scale > wCal)
                wPartTow = wS;
            else
                wPartTow = wCal;
            CreateViewport(db, ArrangeLayoutId, wPartTow + 5, extS.L() / scale + 5,
                Point2d.Origin.C2D(M1 + wPartTow  * 0.5 + 5, 297 - MarginT - hS * 0.5-3),
                extS.GetCenter(), (int)scale);

            double wD = MarginL;
            scale = 1;
            for (int i = 0; i < extD.Count; i++)
            {
                Extents2d ext = extD[i];
                double wDExt = ext.W() / scale;

                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
             Point2d.Origin.C2D(wD + wDExt * 0.5 + 5, MarginB +(h- hP)*0.5),
             ext.GetCenter(), (int)scale);
           
                    if (wD + ext.W() / scale + 10 > wP * i * 0.3)
                    {
                        wD += wP * 0.3;
                    }
                    else
                    {
                        wD += ext.W() / scale + 10;
                    }
     
            }

            //M1 = MarginL + wP;  //B视口位置
            CreateViewport(db, ArrangeLayoutId, ExtCal.W() / scale + 5, ExtCal.L() / scale + 5,
                Point2d.Origin.C2D(M1 + ExtCal.W() / scale * 0.5 + 5, MarginB + ExtCal.L() * 0.5 + 5),
                ExtCal.GetCenter(), (int)scale);

            //PLPloter.AddPloy4ToPaper(Point2d.Origin.C2D(W * 0.5 + MarginL, 297 - MarginT), W * 0.5, W * 0.5, h);
            PLPloter.AddPloy4ToPaper(db,Point2d.Origin.C2D((wTK - 185 - MarginL - MarginR) * 0.5 + MarginL, 297 - MarginT), (wTK - 185 - MarginL - MarginR) * 0.5, (wTK - 185 - MarginL - MarginR) * 0.5, h);
            tKPoint = Point2d.Origin.C2D(wTK- MarginR);
            return ArrangeLayoutId;
        }

        public static ObjectId CreateSerPileCapLayout(Database db, string layoutName,
Extents2d ExtPileCap1, Extents2d ExtPileCap2, Extents2d ExtPileCap3, Extents2d ExtPileCap4, Extents2d ExtPileCap5, Extents2d ExtCal, Extents2d ExtRefer,
double MarginL, double MarginR, double MarginB, double MarginT, double scale, ref Point2d tKPoint)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = "";
            //if (System.IO.File.Exists(Extensions.curTKPath))
            //{
            //    tkPath = Extensions.curTKPath;
            //}
            bool isA1 = false;
            if (Extensions.curMapSheet == "A1")
            {
                isA1 = true;
            }
            scale = 5;
            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
        
            double w1 = ExtPileCap1.W() / scale;  //A视口长度
            double w2 = ExtPileCap2.W() / scale;  //视口位置
            double w3 = ExtPileCap3.W() / scale;  //视口位置
            double w4 = ExtPileCap4.W() / scale;  //视口位置
            double w5 = ExtPileCap5.W() / scale;  //视口位置
            double wcal = ExtCal.W() ;  //视口位置
            double wrefer = ExtRefer.W() ;  //视口位置
            double W = w1 + w2 + w3 + w4 + w5 + wcal + wrefer + 40;
            double wTK = W + MarginL + MarginR + 185;
            int len = (int)(wTK - 25) % 185;
            if ((wTK - 25) % 185 != 0 && len > 100)
                wTK = 25 + ((int)((wTK - 25) / 185) + 1) * 185;
            else
                wTK = 25 + ((int)((wTK - 25) / 185)) * 185;
            ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, true, wTK, 297);
            //ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);



            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), ExtPileCap1.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, ExtPileCap1.W() / scale + 5, ExtPileCap1.L() / scale + 5,
                Point2d.Origin.C2D(MarginL + w1 * 0.5 + 5, h*0.5),
                ExtPileCap1.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, ExtPileCap2.W() / scale + 5, ExtPileCap2.L() / scale + 5,
                 Point2d.Origin.C2D(MarginL + w1 + w2 * 0.5 + 5*2, h * 0.5),
                 ExtPileCap2.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, ExtPileCap3.W() / scale + 5, ExtPileCap3.L() / scale + 5,
           Point2d.Origin.C2D(MarginL + w1 + w2 + w3 * 0.5 + 5*3, h * 0.5),
           ExtPileCap3.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, ExtPileCap4.W() / scale + 5, ExtPileCap4.L() / scale + 5,
       Point2d.Origin.C2D(MarginL + w1 + w2 + w3 + w4 * 0.5 + 5*4, h * 0.5),
       ExtPileCap4.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, ExtPileCap5.W() / scale + 5, ExtPileCap5.L() / scale + 5,
       Point2d.Origin.C2D(MarginL + w1 + w2 + w3 + w4 + w5 * 0.5 + 5*5, h * 0.5),
       ExtPileCap5.GetCenter(), (int)scale);

            scale = 1;
            CreateViewport(db, ArrangeLayoutId, ExtCal.W() / scale + 5, ExtCal.L() / scale + 5,
    Point2d.Origin.C2D(MarginL + w1 + w2 + w3 + w4 + w5+wcal * 0.5 + 5*6, h * 0.5),
    ExtCal.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, ExtRefer.W() / scale + 5, ExtRefer.L() / scale + 5,
    Point2d.Origin.C2D(MarginL + w1 + w2 + w3 + w4 + w5 + wcal+wrefer * 0.5 + 5*7, h * 0.5),
    ExtRefer.GetCenter(), (int)scale);

            PLPloter.AddPloy4ToPaper(db,Point2d.Origin.C2D((wTK-185- MarginL - MarginR) * 0.5 + MarginL, 297 - MarginT), (wTK - 185 - MarginL - MarginR) * 0.5, (wTK - 185 - MarginL - MarginR) * 0.5, h);
            tKPoint = Point2d.Origin.C2D(wTK - MarginR);
            return ArrangeLayoutId;
        }

        #endregion


        #region  墩柱
        public static ObjectId CreatePierLayout(string layoutName,
List<Extents2d> extELst, List<Extents2d> extSLst, List<Extents2d> extSELst, List<Extents2d> extNLst, double MarginL, double MarginR, double MarginB, double MarginT, double scale, int pdfNum = 1, int pageNo = 0,  bool isA1 = false)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
        
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, extELst.Count, pageNo, 0);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, extELst.Count, pageNo, 0);
            }

            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            for (int i = 0; i < extELst.Count; i++)
            {
                Extents2d extE = extELst[i];
                Extents2d extS = extSLst[i];
                Extents2d extSE = extSELst[i];
                Extents2d extN = extNLst[i];
                int divNo = i;
                double EW = extE.W() / scale;
                double EH = extE.L() / scale;
                double ESW = extS.W() / scale;
                double ESEW = extSE.W() / scale;
                double ESEH = extSE.L() / scale;
                double ENW = extN.W() / scale;
                double ENH = extN.L() / scale;
                double w0 = ESEW;
                if (ENW > ESEW)
                    w0 = ENW;
                double w1 = w * EW / (EW + ESW + w0);
                double w2 = w * ESW / (EW + ESW + w0);
                double w3 = w * w0 / (EW + ESW + w0);
                double NH = h * ENH / (ENH + ESEH);
                double SEH = h * ESEH / (ENH + ESEH);
                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * divNo, -297 * pageNo), extE.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, extE.W() / scale + 5, extE.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + 0.5 * w1, MarginB + 0.5 * h).C2D(420 * divNo, -297 * pageNo),
                    extE.GetCenter(), (int)scale);
                CreateViewport(db, ArrangeLayoutId, extS.W() / scale + 5, extS.L() / scale + 5,
               Point2d.Origin.C2D(MarginL + w1 + 0.5 * w2 , MarginB + 0.5 * h).C2D(420 * divNo, -297 * pageNo),
               extS.GetCenter(), (int)scale);
                CreateViewport(db, ArrangeLayoutId, extSE.W() / scale + 5, extSE.L() / scale + 5,
            Point2d.Origin.C2D(MarginL + w1 + w2 + 0.5 * w3, MarginB + NH  + 0.5 * SEH).C2D(420 * divNo, -297 * pageNo),
            extSE.GetCenter(), (int)scale);

                CreateViewport(db, ArrangeLayoutId, extN.W() / scale + 5, extN.L() / scale + 5,
       Point2d.Origin.C2D(MarginL + w1 + w2 + 0.5 * w3, MarginB +(NH+0.5 * SEH- ESEH*0.6 - ENH) + 0.5 * ENH).C2D(420 * divNo, -297 * pageNo),
       extN.GetCenter(), (int)scale);
            }
            return ArrangeLayoutId;
        }


        public static ObjectId CreatePierSubPileLayout(Database db, string layoutName,
List<Extents2d> extALst, List<Extents2d> extBLst, List<Extents2d> extPlanLst, List<Extents2d> extDetailLst,
double MarginL, double MarginR, double MarginB, double MarginT, double scale, int pdfNum = 1, int pageNo = 0, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, extALst.Count, pageNo, 0);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, extALst.Count, pageNo, 0);
            }
            //ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, 1);
            for (int i = 0; i < extALst.Count; i++)
            {
                Extents2d extA = extALst[i];
                Extents2d extB = extBLst[i];
                Extents2d extPlan = extPlanLst[i];
                Extents2d extDetail = extDetailLst[i];
                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);
                double HA = extA.L() / scale;
                double HB = extB.L() / scale;
                double HP = extPlan.L() / scale;
                double h1 = h * HB / (HB + HP);
                double h2 = h * HP / (HB + HP);
                double wA = extA.W() / scale;  //A视口长度
                double wB = extB.W() / scale;  //B视口长度
             
                double wC = extPlan.W() / scale;   //B视口长度
                double w1 = w * wA / (wA + wC);
                double w2 = w * wC / (wA + wC);
                double M1 = MarginL + w1;  //B视口位置
                double M2 = MarginB;  //B视口位置

                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * i, -297 * pageNo), extA.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, extA.W() / scale + 5, extA.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + w1 * 0.5, M2 + 0.5 * h).C2D(420 * i, -297 * pageNo),
                    extA.GetCenter(), (int)scale);

                CreateViewport(db, ArrangeLayoutId, extB.W() / scale + 5, extB.L() / scale + 5,
                    Point2d.Origin.C2D(M1 + wB * 0.5, M2 + 0.5 * h1).C2D(420 * i, -297 * pageNo),
                    extB.GetCenter(), (int)scale);

                CreateViewport(db, ArrangeLayoutId, extPlan.W() / scale + 5, extPlan.L() / scale + 10,
                    Point2d.Origin.C2D(M1 + extPlan.W() / scale * 0.5, M2 + h1 + h2 * 0.5).C2D(420 * i, -297 * pageNo),
                    extPlan.GetCenter(), (int)scale);


                CreateViewport(db, ArrangeLayoutId, extDetail.W() / scale + 5, extDetail.L() / scale + 5,
                   Point2d.Origin.C2D(M1 + wB + 15 + extDetail.W() * 0.5 / scale, MarginB +(h- HP) * 0.5).C2D(420 * i, -297 * pageNo),
                   extDetail.GetCenter(), (int)scale);
            }
            //CreateViewport(db, ArrangeLayoutId, extDetail.W() / scale, extDetail.L() / scale,
            //Point2d.Origin.C2D(MarginL + MarginB*3+ extA.W() / scale+ extB.W() / scale + extDetail.L() / scale * 0.5,
            //M2 + 0.5 * HB),
            //extDetail.GetCenter(), (int)scale);

            return ArrangeLayoutId;
        }


        public static ObjectId CreatePierSubPileCapLayout(Database db, string layoutName,
    List<Extents2d> extTLLst, List<Extents2d> extTRLst, List<Extents2d> extBLLst, List<Extents2d> extBRLst,
    double MarginL, double MarginR, double MarginB, double MarginT, double scale, int pdfNum = 1, int pageNo = 0, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, extTLLst.Count, pageNo, 0);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, extTLLst.Count, pageNo, 0);
            }
            for (int i = 0; i < extTLLst.Count; i++)
            {
                Extents2d extTL= extTLLst[i];
                Extents2d extTR = extTRLst[i];
                Extents2d extBL = extBLLst[i];
                Extents2d extBR = extBRLst[i];
                double VPWidth1 = Math.Max(extTL.W(), extBL.W()) / scale;
                double VPHight1 = Math.Max(extTL.L(), extTR.L()) / scale;
                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);

                double wA = w * (extTL.W() / (extTL.W() + extTR.W()));  //上部左侧视口长度
                double wB = w * (extTR.W() / (extTL.W() + extTR.W()));  //上部右侧视口长度
                double hA = h * (extTL.L() / (extTL.L() + extBL.L()));  //上部左侧视口高度
                double hP = h * (extBL.L() / (extTL.L() + extBL.L()));  //下部左侧视口高度

                double M1 = MarginL + wA;  //上部右侧视口位置
                double M2 = MarginB + hP;  //上部右侧视口位置
                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * i, -297 * pageNo), extTL.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, extTL.W() / scale + 5, extTL.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + wA * 0.5, M2 + 0.5 * hA).C2D(420 * i, -297 * pageNo),
                    extTL.GetCenter(), (int)scale);

                CreateViewport(db, ArrangeLayoutId, extTR.W() / scale + 5, extTR.L() / scale + 5,
                    Point2d.Origin.C2D(M1 + wB * 0.5, M2 + 0.5 * hA).C2D(420 * i, -297 * pageNo),
                    extTR.GetCenter(), (int)scale);

                CreateViewport(db, ArrangeLayoutId, extBL.W() / scale + 5, extBL.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + 0.5 * wA, MarginB + 0.5 * hP).C2D(420 * i, -297 * pageNo),
                    extBL.GetCenter(), (int)scale);


                CreateViewport(db, ArrangeLayoutId, extBR.W() / scale + 5, extBR.L() / scale + 5,
                Point2d.Origin.C2D(M1 + wB * 0.5-10, MarginB + 0.5 * hP).C2D(420 * i, -297 * pageNo),
                extBR.GetCenter(), (int)scale);
            }
            return ArrangeLayoutId;
        }

        public static ObjectId CreatePierSubPierLayout(Database db, string layoutName,
   List<Tuple<Extents2d, Extents2d, Extents2d, Extents2d, Extents2d>> tuPage1Lst, List<Tuple<Extents2d, Extents2d, Extents2d, Extents2d, Extents2d, Extents2d>> tuPage2Lst, List<Tuple<Extents2d>> tuPage3Lst, List<Tuple<Extents2d>> tuPage4Lst,
  double MarginL, double MarginR, double MarginB, double MarginT, double scale,double extendScale = 1, int pdfNum = 1, int pageNo = 0, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1,4 ,tuPage1Lst.Count);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, 4, tuPage1Lst.Count);
            }
            for (int i = 0; i < tuPage1Lst.Count; i++)
            {
                Extents2d extL = tuPage1Lst[i].Item1;
                Extents2d extM = tuPage1Lst[i].Item2;
                Extents2d extTR = tuPage1Lst[i].Item3;
                Extents2d extMR1 = tuPage1Lst[i].Item5;
                Extents2d extMR2 = tuPage1Lst[i].Item4;
                //Extents2d extBR = tuPage1Lst[i].Item6;
                //Extents2d extBR = new Extents2d();

                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);
                double wwR = extMR2.W() > extMR2.W() ? extMR2.W() : extMR2.W();
                double wL = w * (extL.W() / (extL.W() + extM.W() + wwR));  //左侧视口长度
                double wM = w * (extM.W() / (extL.W() + extM.W() + wwR));  //中间视口长度
                double wR = w * (wwR / (extL.W() + extM.W() + wwR));  //右侧视口长度

    
                double hRT = h * (extTR.L() / (extTR.L() + extMR1.L() + extMR2.L() ));  //上部左侧视口高度
                double hRM1 = h * (extMR1.L() / (extTR.L() + extMR1.L() + extMR2.L() ));  //中部左侧视口高度
                double hRM2 = h * (extMR2.L() / (extTR.L() + extMR1.L() + extMR2.L() ));  //中部左侧视口高度
                //double hRB = h * (extBR.L() / (extTR.L() + extMR1.L() + extMR2.L() ));  //下部左侧视口高度

                double M1 = MarginL;  //上部右侧视口位置
                double M2 = MarginB;  //上部右侧视口位置
                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(0, -297 * i), extL.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, extL.W() / scale + 5, extL.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + wL * 0.5, M2 + 0.5 * h).C2D(0, -297 * i),
                    extL.GetCenter(), (int)scale);

                CreateViewport(db, ArrangeLayoutId, extM.W() / scale + 5, extM.L() / scale + 5,
               Point2d.Origin.C2D(MarginL + wL + wM * 0.5-20, M2 + 0.5 * h).C2D(0, -297 * i),
               extM.GetCenter(), (int)scale);

                //   CreateViewport(db, ArrangeLayoutId, extBR.W() / scale + 5, extBR.L() / scale + 5,
                //Point2d.Origin.C2D(MarginL + wL + wM + wR * 0.5 - 10, M2 + 0.5 * hRB+5).C2D(0, -297 * i),
                //extBR.GetCenter(), (int)scale);
                CreateViewport(db, ArrangeLayoutId, extMR1.W() / (scale * extendScale) + 5, extMR1.L() / (scale * extendScale) + 5,
      Point2d.Origin.C2D(MarginL + wL + wM + wR * 0.5 - 20, M2  + 0.5 * hRM1+4).C2D(0, -297 * i),
      extMR1.GetCenter(), scale*extendScale);

                CreateViewport(db, ArrangeLayoutId, extMR2.W() / (scale * extendScale) + 5, extMR2.L() / (scale * extendScale) + 5,
     Point2d.Origin.C2D(MarginL + wL + wM + wR * 0.5 - 20, M2  + hRM1 + 0.5 * hRM2+3 ).C2D(0, -297 * i),
     extMR2.GetCenter(), scale * extendScale);

                CreateViewport(db, ArrangeLayoutId, extTR.W() / (scale * extendScale) + 5, extTR.L() / (scale * extendScale) + 5,
      Point2d.Origin.C2D(MarginL + wL + wM + wR * 0.5 - 20, M2  + hRM1 + hRM2 + 0.5 * hRT+1).C2D(0, -297 * i),
      extTR.GetCenter(), scale*extendScale);
            }

            for (int i = 0; i < tuPage2Lst.Count; i++)
            {
                Extents2d extL = tuPage2Lst[i].Item1;
                Extents2d extM = tuPage2Lst[i].Item2;
                Extents2d extTR = tuPage2Lst[i].Item3;
                Extents2d extMR1 = tuPage2Lst[i].Item5;
                Extents2d extMR2 = tuPage2Lst[i].Item4;
                Extents2d extBR = tuPage2Lst[i].Item6;

                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);

                //double wL = w * (extL.W() / (extL.W() + extM.W() + extMR2.W()));  //左侧视口长度
                //double wM = w * (extM.W() / (extL.W() + extM.W() + extMR2.W()));  //中间视口长度
                //double wR = w * (extMR2.W() / (extL.W() + extM.W() + extMR2.W()));  //右侧视口长度
                double wwR = extMR2.W() > extBR.W() ? extMR2.W() : extBR.W();
                double wL = w * (extL.W() / (extL.W() + extM.W() + wwR));  //左侧视口长度
                double wM = w * (extM.W() / (extL.W() + extM.W() + wwR));  //中间视口长度
                double wR = w * (wwR / (extL.W() + extM.W() + wwR));  //右侧视口长度

                double hRT = h * (extTR.L() / (extTR.L() + extMR1.L() + extMR2.L() + extBR.L()));  //上部左侧视口高度
                double hRM1 = h * (extMR1.L() / (extTR.L() + extMR1.L() + extMR2.L() + extBR.L()));  //中部左侧视口高度
                double hRM2 = h * (extMR2.L() / (extTR.L() + extMR1.L() + extMR2.L() + extBR.L()));  //中部左侧视口高度
                double hRB = h * (extBR.L() / (extTR.L() + extMR1.L() + extMR2.L() + extBR.L()));  //下部左侧视口高度

                double M1 = MarginL;  //上部右侧视口位置
                double M2 = MarginB;  //上部右侧视口位置
                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                #endregion
                CreateViewport(db, ArrangeLayoutId, extL.W() / scale + 5, extL.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + wL * 0.5, M2 + 0.5 * h).C2D(420, -297 * i),
                    extL.GetCenter(), (int)scale);
               
                CreateViewport(db, ArrangeLayoutId, extM.W() / scale + 5, extM.L() / scale + 5,
               Point2d.Origin.C2D(MarginL + wL + wM * 0.5 - 20, M2 + 0.5 * h).C2D(420, -297 * i),
               extM.GetCenter(), (int)scale);


                CreateViewport(db, ArrangeLayoutId, extBR.W() / (scale ) + 5, extBR.L() / (scale ) + 5,
             Point2d.Origin.C2D(MarginL + wL + wM + wR * 0.5 - 10, M2 + 0.5 * hRB + 5).C2D(420, -297 * i),
             extBR.GetCenter(), (int)scale);

                if(hRM1>0)
                CreateViewport(db, ArrangeLayoutId, extMR1.W() / (scale * extendScale) + 5, extMR1.L() / (scale * extendScale) + 5,
      Point2d.Origin.C2D(MarginL + wL + wM + wR * 0.5 - 20, M2 + hRB + 0.5 * hRM1 + 1).C2D(420, -297 * i),
      extMR1.GetCenter(), scale * extendScale);
                if (hRM2 > 0)
                    CreateViewport(db, ArrangeLayoutId, extMR2.W() / (scale * extendScale) + 5, extMR2.L() / (scale * extendScale) + 5,
     Point2d.Origin.C2D(MarginL + wL + wM + wR * 0.5 - 20, M2 + hRB + hRM1 + 0.5 * hRM2 + 1).C2D(420, -297 * i),
     extMR2.GetCenter(), scale * extendScale);
                if (hRT > 0)
                    CreateViewport(db, ArrangeLayoutId, extTR.W() / (scale * extendScale) + 5, extTR.L() / (scale * extendScale) + 5,
      Point2d.Origin.C2D(MarginL + wL + wM + wR * 0.5 - 20, M2 + hRB + hRM1 + hRM2 + 0.5 * hRT ).C2D(420, -297 * i),
      extTR.GetCenter(), scale * extendScale);
            }

            for (int i = 0; i < tuPage3Lst.Count; i++)
            {
                Extents2d ext= tuPage3Lst[i].Item1;
            
                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);

             

                double M1 = MarginL;  //上部右侧视口位置
                double M2 = MarginB;  //上部右侧视口位置
                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + w * 0.5, M2 + 0.5 * h).C2D(420 * 2, -297 * i),
                    ext.GetCenter(), (int)scale);
                #endregion
               
                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
      Point2d.Origin.C2D(MarginL + w * 0.5 , M2  + 0.5 * h).C2D(420*2, -297 * i),
      ext.GetCenter(), (int)scale);
            }
            for (int i = 0; i < tuPage4Lst.Count; i++)
            {
                Extents2d ext = tuPage4Lst[i].Item1;

                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);



                double M1 = MarginL;  //上部右侧视口位置
                double M2 = MarginB;  //上部右侧视口位置
                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + w * 0.5, M2 + 0.5 * h).C2D(420 * 3, -297 * i),
                    ext.GetCenter(), (int)scale);
                #endregion

                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
      Point2d.Origin.C2D(MarginL + w * 0.5, M2 + 0.5 * h).C2D(420 * 3, -297 * i),
      ext.GetCenter(), (int)scale);
            }
            return ArrangeLayoutId;
        }

        public static ObjectId CreatePierBeamLayout(Database db, string layoutName,
List<Extents2d> extLLst, List<Extents2d> extMLst, List<Extents2d> extRLst,
double MarginL, double MarginR, double MarginB, double MarginT, double scale, int pdfNum = 1, int pageNo = 0, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            HostApplicationServices.WorkingDatabase = db;
           string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, extLLst.Count, pageNo, 0);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, extLLst.Count, pageNo, 0);
            }
            for (int i = 0; i < extLLst.Count; i++)
            {
                Extents2d extL = extLLst[i];
                Extents2d extM = extMLst[i];
                Extents2d extR = extRLst[i];
          
                double w = (420 - MarginL - MarginR);
                double h = (297 - MarginB - MarginT);

                double wL = w * (extL.W() / (extL.W() + extR.W()+ extM.W()));  //上部左侧视口长度
                double wM = w * (extM.W() / (extL.W() + extR.W() + extM.W()));  //上部右侧视口长度
                double wR = w * (extR.W() / (extL.W() + extR.W() + extM.W()));  //上部右侧视口长度

                double M1 = MarginL ;  //上部右侧视口位置
                double M2 = MarginB;  //B视口位置
                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * i, -297 * pageNo), extL.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, extL.W() / scale + 5, extL.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + wL * 0.5, M2 + 0.5 * h).C2D(420 * i, -297 * pageNo),
                    extL.GetCenter(), (int)scale);

                CreateViewport(db, ArrangeLayoutId, extM.W() / scale + 5, extM.L() / scale + 5,
                    Point2d.Origin.C2D(M1 + wL+wM * 0.5, M2 + 0.5 * h).C2D(420 * i, -297 * pageNo),
                    extM.GetCenter(), (int)scale);

                CreateViewport(db, ArrangeLayoutId, extR.W() / scale + 5, extR.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + wL + wM + 0.5 * wR, MarginB + 0.5 * h).C2D(420 * i, -297 * pageNo),
                    extR.GetCenter(), (int)scale);

            }
           
            return ArrangeLayoutId;
        }
        #endregion

        #region 机场桥
        public static ObjectId CreateAviationBridgeLayout(Database db, string layoutName,
Extents2d extE, Extents2d extS,
double MarginL, double MarginR, double MarginB, double MarginT, double scale, int pdfNum = 1, int pageNo = 0, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            HostApplicationServices.WorkingDatabase = db;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, pdfNum, pageNo, 0);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, pdfNum, pageNo, 0);
            }


            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);


            double wL0 = extE.W() / scale;
            double scaleS = 80;
            double wR0 = extS.W() / scaleS;
            //double wL = w * wL0 / (wL0 + wR0);
            //double wR = w * wR0 / (wL0 + wR0);
            double M1 = MarginL;  //上部右侧视口位置
            double M2 = MarginB;  //B视口位置
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(), extE.GetCenter(), (int)scale);
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
       Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420), extE.GetCenter(), (int)scale);
            #endregion

            CreateViewport(db, ArrangeLayoutId, extE.W() / scale + 5, extE.L() / scale + 5,
               Point2d.Origin.C2D(MarginL + 5 + w * 0.5, M2 + 0.5 * h).C2D(),
               extE.GetCenter(), (int)scale);

            //double wR = extS.W() / scale;
            CreateViewport(db, ArrangeLayoutId, wR0*1.2 + 15, extS.L() / scaleS + 15,
              Point2d.Origin.C2D(MarginL +  w * 0.5, M2 + h * 0.5).C2D(420),  
              extS.GetCenter(), (int)scaleS);


            return ArrangeLayoutId;
        }   

        public static ObjectId CreateAviationBridgeLayoutOld(Database db, string layoutName,
Extents2d extE, Extents2d extP, Extents2d extN, Extents2d extS,
double MarginL, double MarginR, double MarginB, double MarginT, double scale, int pdfNum = 1, int pageNo = 0, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            HostApplicationServices.WorkingDatabase = db;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, 1, pageNo, 0);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, 1, pageNo, 0);
            }


            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);

            double hT = h * (extE.L() / (extE.L() + extP.L() + extN.L()));  //上部左侧视口长度
            double hM = h * (extP.L() / (extE.L() + extP.L() + extN.L()));  //上部右侧视口长度
            double hB = h * (extP.L() / (extE.L() + extP.L() + extN.L()));  //上部右侧视口长度
            double wL = extE.W() / scale;


            double M1 = MarginL;  //上部右侧视口位置
            double M2 = MarginB;  //B视口位置
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(), extE.GetCenter(), (int)scale);
            #endregion
            CreateViewport(db, ArrangeLayoutId, extN.W() / scale + 5, extN.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + wL * 0.5, M2 + 0.5 * hB).C2D(),
                    extN.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extP.W() / scale + 5, extP.L() / scale + 5,
            Point2d.Origin.C2D(MarginL + wL * 0.5, M2 + hB + 0.5 * hM).C2D(),
            extP.GetCenter(), (int)scale);

            CreateViewport(db, ArrangeLayoutId, extE.W() / scale + 5, extE.L() / scale + 5,
               Point2d.Origin.C2D(MarginL + wL * 0.5, M2 + hB + hM + 0.5 * hT).C2D(),
               extE.GetCenter(), (int)scale);

            scale = 100;
            double wR = extS.W() / scale;
            CreateViewport(db, ArrangeLayoutId, extS.W() / scale + 5, extS.L() / scale + 5,
              Point2d.Origin.C2D(MarginL + wL + wR * 0.5, h * 0.5).C2D(),
              extS.GetCenter(), (int)scale);


            return ArrangeLayoutId;
        }


        public static ObjectId CreateSteelTowerLayout(Database db, string layoutName, Extents2d extTower,
List<Extents2d> extLst, double MarginL, double MarginR, double MarginB, double MarginT, double scale, int index = 0, bool isA1 = false)
        {
            //Database db = HostApplicationServices.WorkingDatabase;
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, extLst.Count+1, index);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, extLst.Count+1, index);
            }
            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT);
            double ww = extTower.W() / scale;
            double hh = extTower.L() / scale;
            #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
            CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
         Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB), extTower.GetCenter(), (int)scale);
            #endregion
            CreateViewportRotate(db, ArrangeLayoutId, extTower.W() / scale + 15, extTower.L() / scale + 15,
                Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * h),
                extTower.GetCenter(), (int)scale);

            
            for (int i = 0; i < extLst.Count; i++)
            {
                Extents2d ext = extLst[i];


                //double w = (420 - MarginL - MarginR);
                //double h = (297 - MarginB - MarginT);

                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * (i+1), -297 * (index - 1)), ext.GetCenter(), (int)scale);
                #endregion
                CreateViewport(db, ArrangeLayoutId, ext.W() / scale + 5, ext.L() / scale + 5,
                    Point2d.Origin.C2D(MarginL + 0.5 * w, MarginB + 0.5 * h).C2D(420 * (i + 1), -297 * (index - 1)),
                    ext.GetCenter(), (int)scale);
            }
            return ArrangeLayoutId;
        }
        public static ObjectId CreateAbutmentLayout(Database db, string layoutName, List<Tuple<int, double, List<Extents2d>>> tuPage,
double MarginL, double MarginR, double MarginB, double MarginT,  bool isA1 = false)
        {
           
            
            ObjectId ArrangeLayoutId;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, tkPath, isA1, tuPage.Count);
                //ArrangeLayoutId = db.CreatLayout(layoutName, "",true,1422,297, isA1, 1);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayout(layoutName, "", isA1, tuPage.Count);
            }
            for (int i = 0; i < tuPage.Count; i++)
            {
                int page = tuPage[i].Item1;
                double  scale= tuPage[i].Item2;
                if (page == 1 || page == 3)
                {
                    List<Extents2d> lst = tuPage[i].Item3;
                    Extents2d extTL = lst[0];
                    Extents2d extBL = lst[1];
                    Extents2d extR = lst[2];
                    double VPWidth1 = Math.Max(extTL.W(), extBL.W()) / scale;
                    double VPHight1 = Math.Max(extTL.L(), extR.L()) / scale;
                    double w = (420 - MarginL - MarginR);
                    double h = (297 - MarginB - MarginT);

                    double wA = w * (extTL.W() / (extTL.W() + extR.W()));  //上部左侧视口长度
                    double wB = w * (extR.W() / (extTL.W() + extR.W()));  //上部右侧视口长度
                    double hA = h * (extTL.L() / (extTL.L() + extBL.L()));  //上部左侧视口高度
                    double hP = h * (extBL.L() / (extTL.L() + extBL.L()));  //下部左侧视口高度

                    double M1 = MarginL + wA;  //上部右侧视口位置
                    double M2 = MarginB + hP;  //上部右侧视口位置
                    #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                    CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
                 Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420*i), extTL.GetCenter(), (int)scale);
                    #endregion
                    CreateViewport(db, ArrangeLayoutId, extTL.W() / scale + 5, extTL.L() / scale + 5,
                        Point2d.Origin.C2D(MarginL + wA * 0.5, M2 + 0.5 * hA).C2D(420 * i),
                        extTL.GetCenter(), (int)scale);


                    CreateViewport(db, ArrangeLayoutId, extBL.W() / scale + 5, extBL.L() / scale + 5,
                        Point2d.Origin.C2D(MarginL + 0.5 * wA, MarginB + 0.5 * hP).C2D(420 * i),
                        extBL.GetCenter(), (int)scale);


                    CreateViewport(db, ArrangeLayoutId, extR.W() / scale + 5, extR.L() / scale + 5,
                    Point2d.Origin.C2D(M1 + wB * 0.5, MarginB + 0.5 * h).C2D(420 * i),
                    extR.GetCenter(), (int)scale);
                }
                else
                {
                    List<Extents2d> lst = tuPage[i].Item3;
                    Extents2d extL = lst[0];
                    Extents2d extR = lst[1];
               
                    double w = (420 - MarginL - MarginR);
                    double h = (297 - MarginB - MarginT);

                    double wA = w * (extL.W() / (extL.W() + extR.W()));  //上部左侧视口长度
                    double wB = w * (extR.W() / (extL.W() + extR.W()));  //上部右侧视口长度
                  

                    double M1 = MarginL + wA;  //上部右侧视口位置
                    #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                    CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
                 Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(420 * i), extL.GetCenter(), (int)scale);
                    #endregion
                    CreateViewport(db, ArrangeLayoutId, extL.W() / scale + 5, extL.L() / scale + 5,
                        Point2d.Origin.C2D(MarginL + wA * 0.5, MarginB + 0.5 * h).C2D(420 * i),
                        extL.GetCenter(), (int)scale);


                    CreateViewport(db, ArrangeLayoutId, extR.W() / scale + 5, extR.L() / scale + 5,
                    Point2d.Origin.C2D(M1 + wB * 0.5, MarginB + 0.5 * h).C2D(420 * i),
                    extR.GetCenter(), (int)scale);
                }
            }
            return ArrangeLayoutId;
        }
        #region 钢桁架
        public static ObjectId CreateTrussBeamStructureLayout(Database db, string layoutName,
List<Extents2d> extLst, 
double MarginL, double MarginR, double MarginB, double MarginT, double scale, int pdfNum = 1, int pageNo = 0, bool isA1 = false)
        {
            ObjectId ArrangeLayoutId;
            HostApplicationServices.WorkingDatabase = db;
            string tkPath = Extensions.curTKPath;
            if (System.IO.File.Exists(tkPath))
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, tkPath, isA1, 1, pageNo, 0);
            }
            else
            {
                ArrangeLayoutId = db.CreatLayoutNew(layoutName, "", isA1, 1, pageNo, 0);
            }

            Extents2d extE = extLst[0];
            double w = (420 - MarginL - MarginR);
            double h = (297 - MarginB - MarginT)-20;
            double hDiv = (h-15) * ((double)(1) / extLst.Count);
            for (int i = 0; i < extLst.Count; i++)
            {
                extE = extLst[extLst.Count-1-i];
                double M1 = MarginL;  //上部右侧视口位置
                double M2 = MarginB;  //B视口位置
                #region 无效视口方便自动保存，不加这一个自动保存数据视口消失
                CreateViewport(db, ArrangeLayoutId, 0.1, 0.1,
             Point2d.Origin.C2D(w * 0.5 + MarginL, MarginB).C2D(), extE.GetCenter(), (int)scale);
                #endregion

                CreateViewport(db, ArrangeLayoutId, extE.W() / scale + 5, extE.L() / scale + 5,
                   Point2d.Origin.C2D(MarginL + 5 + w * 0.5, M2 +15+ 0.5 * hDiv +(i)* hDiv).C2D(),
                   extE.GetCenter(), (int)scale);
            }
            return ArrangeLayoutId;
        }

        #endregion
        #endregion
        #region 批量生成PDF
        public static void PlotDrawingByTK(this Database db, string Name, string pageSize, string styleSheet, string device,string dwgFile,out string pdfPsth, ref List<string> fileList, bool isA1 = false)
        {
            Layout lay;
            ObjectId curLayId;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord blockTableRecord = tr.GetObject(blockTable[BlockTableRecord.PaperSpace], OpenMode.ForRead) as BlockTableRecord;
                DBDictionary lays = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary;
                HostApplicationServices.WorkingDatabase = db;
                var acLayoutMgr = LayoutManager.Current;
                if (!lays.Contains(Name))
                {
                    curLayId = LayoutManager.Current.CreateLayout(Name);
                }
                else
                {
                    curLayId = LayoutManager.Current.GetLayoutId(Name);
                }

                LayoutManager.Current.CurrentLayout = Name;
                lay = (Layout)tr.GetObject(curLayId, OpenMode.ForWrite);

                #region 初始打印信息
                using (var ps = new PlotSettings(lay.ModelType))
                {
                    ps.CopyFrom(lay);
                    var psv = PlotSettingsValidator.Current;
                    //psv.Dispose();
                    // Set the device
                    var devs = psv.GetPlotDeviceList();
                    if (ps.PlotConfigurationName != device)
                    {
                        if (devs.Contains(device))
                        {
                            if (ps.PlotConfigurationName != device)
                                psv.SetPlotConfigurationName(ps, device, null);
                            psv.RefreshLists(ps);
                        }

                        // Set the media name/size
                        var mns = psv.GetCanonicalMediaNameList(ps);
                        if (mns.Contains(pageSize))
                        {
                            if (ps.CanonicalMediaName != pageSize)
                                psv.SetCanonicalMediaName(ps, pageSize);
                        }
                        //设置打印区域SetPlotType
                        //psv.SetPlotType(ps, PlotType.Window);
                        //psv.SetPlotWindowArea(ps, extents);
                        if (isA1)
                            psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(841, 594)));
                        else
                            psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(420, 297)));
                        //psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(520, 297)));

                        psv.RefreshLists(ps);
                        psv.SetPlotRotation(ps, PlotRotation.Degrees000);

                        //psv.SetPlotCentered(ps, true);
                        psv.SetCustomPrintScale(ps, new CustomScale(1, 1));
                        psv.SetPlotType(ps, PlotType.Window);
                        psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);//设置的单位
                        psv.SetStdScaleType(ps, StdScaleType.StdScale1To1);//设置比例
                                                                           //psv.SetPlotCentered(ps, true);
                                                                           // Set the pen settings


                        var ssl = psv.GetPlotStyleSheetList();
                        if (ssl.Contains(styleSheet))
                        {
                            psv.SetCurrentStyleSheet(ps, styleSheet);
                        }
                        // Copy the PlotSettings data back to the Layout
                    }
                    var upgraded = false;
                    if (!lay.IsWriteEnabled)
                    {
                        lay.UpgradeOpen();
                        upgraded = true;
                    }
                    lay.CopyFrom(ps);
                    if (upgraded)
                    {
                        lay.DowngradeOpen();
                    }
                }
                #endregion

                #region  打印范围
                //List<object[]> ls_rec = new List<object[]>();
                List<Extents2d> ls_rec = new List<Extents2d>();
                foreach (ObjectId entityId in blockTableRecord)
                {

                    Entity entity = tr.GetObject(entityId, OpenMode.ForRead) as Entity;


                    dynamic cadObject = entity;
                    string Layername = cadObject.Layer;//获取layer名称
                    if (Layername != "H文本"&& Layername != "Defpoints")
                    {
                    }
                    if (Layername == "H图框"|| Layername == "H不打印图框")
                    {

                        dynamic acadMLine = cadObject;
                        try
                        {
                            //coordinates = acadMLine.Coordinates;
                            BlockReference acadBlock = (BlockReference)cadObject;
                            Extents3d exT = acadBlock.GeometryExtentsBestFit();
                            Extents2d ext2d = new Extents2d(exT.MinPoint.C2D(), exT.MaxPoint.C2D());

                            ls_rec.Add(ext2d);
                        }
                        catch (System.Exception ex)
                        {

                        }
                    }
                }

                #endregion

                #region 批量输出
                int pdfNum = 0;
                FileInfo file = new FileInfo(dwgFile);
                string fileName = file.Name.Replace(file.Extension,"");
                string dir = file.DirectoryName + "\\PDF\\";
                new WriteLogs().creatFolder(dir );
                string filePath = dir+ fileName + ".pdf";
                //List<string> fileList = new List<string>();
                foreach (var item in ls_rec)
                {
                    pdfNum++;
                    using (var ps = new PlotSettings(lay.ModelType))
                    {
                        ps.CopyFrom(lay);

                        var psv = PlotSettingsValidator.Current;

                        // Set the device
                        var devs = psv.GetPlotDeviceList();
                        if (ps.PlotConfigurationName != device)
                        {
                            if (devs.Contains(device))
                            {
                                if (ps.PlotConfigurationName != device)
                                    psv.SetPlotConfigurationName(ps, device, null);
                                psv.RefreshLists(ps);
                            }
                        }

                        var mns = psv.GetCanonicalMediaNameList(ps);
                        if (mns.Contains(pageSize))
                        {
                            if (ps.CanonicalMediaName != pageSize)
                                psv.SetCanonicalMediaName(ps, pageSize);
                        }


                        psv.RefreshLists(ps);
                        psv.SetPlotWindowArea(ps, item);

                        //psv.SetPlotWindowArea(ps, new Extents2d(new Point2d(0, 0), new Point2d(520, 297)));
                        psv.SetPlotRotation(ps, PlotRotation.Degrees000);

                        psv.SetPlotCentered(ps, true);
                        psv.SetCustomPrintScale(ps, new CustomScale(1, 1));
                        //psv.SetPlotType(ps, PlotType.Window);
                        psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);//设置的单位
                        psv.SetStdScaleType(ps, StdScaleType.StdScale1To1);//设置比例
                                                                           //psv.SetPlotCentered(ps, true);
                                                                           // Set the pen settings



                        //psv.SetPlotType(ps, PlotType.Window);
                        var ssl = psv.GetPlotStyleSheetList();
                        if (ssl.Contains(styleSheet))
                        {
                            psv.SetCurrentStyleSheet(ps, styleSheet);
                        }
                        psv.RefreshLists(ps);

                        var upgraded = false;
                        if (!lay.IsWriteEnabled)
                        {
                            lay.UpgradeOpen();
                            upgraded = true;
                        }
                        lay.CopyFrom(ps);
                        if (upgraded)
                        {
                            lay.DowngradeOpen();
                        }
                        mPDFExportParams par = new mPDFExportParams();
                        par.BackgroundColor = Color.FromArgb(0, Color.White);

                        StreamBuf buf;
                        try
                        {

                            filePath = dir + fileName + " " + pdfNum.ToString() + ".pdf";
                            fileList.Add(filePath);

                            //public FileStreamBuf(string pcFilename, bool openForRead, FileShareMode nShareMode, FileCreationDisposition nCreationDisposition);
                            FileStreamBuf fbuf = new FileStreamBuf(filePath, false, FileShareMode.DenyNo, FileCreationDisposition.CreateAlways);
                            buf = fbuf;


                            par.Flags = (PDFExportFlags.EmbededTTF)
                                          | (PDFExportFlags.SHXTextAsGeometry)
                                          | (PDFExportFlags.TTFTextAsGeometry)
                                           //| (PDFExportFlags.SimpleGeomOptimization)
                                           //  | (PDFExportFlags.ZoomToExtentsMode)
                                           | (PDFExportFlags.EnableLayers);

                            par.Database = db;
                            par.Author = "wn";
                            par.Title = "DWG To PDF";
                            par.Creator = "wn";
                            par.Versions = PDFExportVersions.PDFv1_4;

                            //db.Filename;
                            par.OutputStream = buf;
                            //db.GetLayoutId("图纸").

                            Color[] CurPalette = new Color[1] { Color.White };// {Color.FromArgb(0, Color.White) };
                            par.Palette = CurPalette;

                            StringCollection strColl = new StringCollection();

                            using (DBDictionary layouts = (DBDictionary)lay.Database.LayoutDictionaryId.GetObject(OpenMode.ForRead))
                            {
                                foreach (DBDictionaryEntry entry in layouts)
                                {
                                    if (entry.Key.ToUpper() != "MODEL")
                                        strColl.Add(entry.Key);
                                }
                            }



                            int nPages = Math.Max(1, ls_rec.Count);
                            PageParamsCollection pParCol = new PageParamsCollection();
                            for (int i = 0; i < ls_rec.Count; ++i)
                            {
                                PageParams pp = new PageParams();
                                pp.setParams(ls_rec[i].MaxPoint.X - ls_rec[i].MinPoint.X, ls_rec[i].MaxPoint.Y - ls_rec[i].MinPoint.Y);
                                pParCol.Add(pp);
                            }
                            par.PageParams = pParCol;
                            Export_Import.ExportPDF(par);

                            par.Dispose();
                            buf.Dispose();
                            fbuf.Dispose();
                            psv.Dispose();
                            ps.Dispose();
                            //db.Dispose();
                        }
                        catch (Teigha.Runtime.Exception ex)
                        {

                        }

                        // Copy the PlotSettings data back to the Layout

                            
                    }
                }
                #endregion

                #region 合并pdf                
                if (ls_rec.Count > 1)
                {
                    //filePath = dir + fileName + ".pdf";
                    //ITextPdfHelper.mergePDFFiles(fileList, filePath);
                }
                pdfPsth = filePath;
                #endregion
            }
        }
        #endregion
    }
}
